﻿using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

namespace TradeMo
{
    public class VisibilityConverter : IValueConverter
    {
        private static bool IsVisibilityInverted(object parameter)
        {
            return (GetVisibilityMode(parameter) == Visibility.Collapsed);
        }

        private static Visibility GetVisibilityMode(object parameter)
        {
            Visibility mode = Visibility.Visible;
            if (parameter != null)
            {
                if (parameter is Visibility)
                {
                    mode = (Visibility)parameter;
                }
                else
                {
                    try
                    {
                        mode = (Visibility)Enum.Parse(typeof(Visibility), parameter.ToString(), true);
                    }
                    catch (FormatException e)
                    {
                        throw new FormatException("Invalid Visibility specified as the ConverterParameter.  Use Visible or Collapsed.", e);
                    }
                }
            }

            return mode;
        }


        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            bool isVisible = false;
            if (value is bool)
                isVisible = (bool)value;
            else if (value is int)
                isVisible = ((int)value != 0);
            else if (value != null)
                isVisible = true;

            if (IsVisibilityInverted(parameter))
                isVisible = !isVisible;
            return (isVisible ? Visibility.Visible : Visibility.Collapsed);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            bool isVisible = ((Visibility)value == Visibility.Visible);
            if (IsVisibilityInverted(parameter))
                isVisible = !isVisible;
            return isVisible;
        }
    }
}
